import IconFont from '@/components/IconFont';
import CommonLoading from '@/components/CommonLoading';
import GoodsListModal from '@/pages/GoodsModule/combinationGoods/component/GoodsListModal'
import BatchInputModal from '@/pages/OrderModule/common/components/BatchInputModal';
import { CommonForm } from '@/pages/OrderModule/common/components/CommonForm';
import { CommonModal } from '@/pages/OrderModule/common/components/CommonModal';
import ResetStyle from '@/pages/OrderModule/common/components/ResetStyle';
import SubTitle from '@/pages/OrderModule/common/components/SubTitle';
import { Form, Input, Radio, Space, message, Modal, Button, Alert, InputNumber } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import OrderAreaRadioGroup from '../../components/OrderAreaRadioGroup1';
import OrderAreaRadioGroup1Switch from '../../components/OrderAreaRadioGroup1Switch';
import OrderNumberCount from '../../components/OrderNumberCount';
import { batchExchangeGoods, modifyGoodsOp, saveFormulaApi } from '../../../../services';
import ConfirmPayModal from '../../components/ConfirmPayModal';
import Styles from './index.module.less'
import { formatAmount, cpText } from '@/utils/utils.jsx';
import { queryPageConfig, saveOrUpdatePageConfig } from '@/services/common';

//字符串拆分为（商品编码*数量）list
const stringFormatArr = (str) => {
  return str ? str.replaceAll(' ', '').replaceAll('，', ',').split(',') : [];
}

const formatFunc = (str) => {
  let tips = false;
  if(str?.length){
    const allList = stringFormatArr(str);
    for(let i = 0; i < allList.length; i++){
      const arr = allList[i].split('*'), len = arr.length;

    }
  }
}

//覆盖操作
const combindStr = (oldValue, newValue) => {
  const obj = {}, oldArr = stringFormatArr(oldValue), newArr = stringFormatArr(newValue), allArr = [...oldArr, ...newArr];
  allArr.map(item=>{
    const arr = item.split('*');
    obj[arr[0]] = arr[1] || 1;
  })
  return Object.keys(obj).map(item=>item + "*" + obj[item]).join(',');
}
//覆盖操作
const combindStr2 = (oldValue, newValue) => {
  const obj = {}, oldArr = stringFormatArr(oldValue), newArr = stringFormatArr(newValue), allArr = [...oldArr, ...newArr];
  allArr.map(item=>{
    const arr = item.split('*');
    obj[arr[0]] = arr[1] || 1;
  })
  return Object.keys(obj).map(item=>item).join(',');
}

/** 批量修改商品 */
function UpdateGoodsModal(props) {
  const [form] = Form.useForm();
  const addStrategyWatch = Form.useWatch('addStrategy', form);

  const [loading, setLoading]=useState(false);
  const [showNumber, setShowNumber] = useState({});
  const [visible, setVisible] = useState(false);
  const filterIds = useRef(undefined);
  const stageParams = useRef({});
  const operatorType = useRef('add');

  const [amountObj, setAmountObj] = useState(null);

  const { orderList, searchForm, selectKeys, items = {} } = props;

  useEffect(() => {
    getFormula()
  }, [])
  
  const getFormula = async () => {
    const { success, data = {} } = await queryPageConfig({ 
      scope: 2,
      page: 'orderPageList',
      type: 'goods-formula',
     });
    if(success) {
      const list = JSON.parse(data.param)
      console.log(list, 333)
      if(list.length) {
        form.setFieldValue('users', list)
      }
    }

  }

  function handleOk() {
    if(!showNumber.total){
      return message.info('暂无可处理的订单！')
    }
    if(form.getFieldValue('addStrategy') == 3) { // 按公式换货，先保存公式
      orderAreaRadioSwitchProps.saveFormula(1)
    }
    form.validateFields().then(async values =>{
      console.log('提交参数--', values)
      const { addSkuCodes, delSkuCodes, addStrategy, users, prices } = values;
      setLoading(true);
      const params = {
        exchangeType: addStrategy,
        // replaceSysGoodsCodeList: [],
        // replacedSysGoodsCodeList: [],
        replaceSysGoodsCodeList: addSkuCodes ? stringFormatArr(addSkuCodes) : undefined,
        replacedSysGoodsCodeList: delSkuCodes ? stringFormatArr(delSkuCodes) : undefined,
        orderIds: selectKeys,
        // formulaList: [],
        formulaList: users.map(item => item?.first2).filter(item => item),
        purchasePrice: prices,
        // 'radio-group': undefined
      }
      // Modal.info({
      //   title: '换商品提示',
      //   content: (
      //     <div>
      //       <div className='common-color9'>修改商品失败！</div>
      //       <div>失败原因：</div>
      //       {
      //         [1].map(v => {
      //           return (
      //             <div key={v}>{v}</div>
      //           )
      //         })
      //       }
      //       <div>{1}</div>
      //     </div>
      //   )
      // })
      console.log(params, 111)
      const { data, success, msg } = await batchExchangeGoods(params);
      console.log(data, success)
      setLoading(false);
      if(success && data){
        
        if(data.msg) {
          return Modal.confirm({
            title: '换商品提示',
            okText: '知道了',
            // cancelText: '批量复制订单号',
            onCancel:(close) => {
              // cpText('M12323')
              // close()
              props.handleCancel() // 关闭换货弹窗
              return Promise.resolve()
            },
            onOk: () => {
              props.handleOk() // 关闭换货弹窗
            },
            content: (
              <div>
                <div className={Styles.flexwrap}>
                  <div>成功数：<span className={Styles['success']}>{data.successNum}</span></div>
                  <div>失败数：<span className={Styles['fail']}>{data.failNum}</span></div>
                </div>
                {data.failNum && <div style={{fontSize: 12, marginTop:10}}>
                  失败原因可能是：
                  {data.replacedNotExistOrderNoList.length > 0 && <div>被替换的商品编码不存在：{data.replacedNotExistOrderNoList.toString()}</div>}
                  {data.replaceNotExistOrderNoList.length > 0 && <div>替换的商品编码不存在：{data.replaceNotExistOrderNoList.toString()}</div>}
                  {data.formulaNotExistOrderNoList.length > 0 && <div>公式里填写的以下商品编码不存在：{data.formulaNotExistOrderNoList.toString()}</div>}
                  {data.replacedNotExistOrderNoList.length == 0 && 
                    data.replaceNotExistOrderNoList.length == 0 && 
                    data.formulaNotExistOrderNoList.length == 0 && 
                    <div>订单无对应的被替换的商品编码和数量，或订单是异常已支付的代发订单</div>}
                </div>}
              </div>
            )
          })
        } else {
          return Modal.confirm({
            title: '换商品提示',
            okText: '知道了',
            // cancelText: '批量复制订单号',
            onCancel:(close) => {
              // cpText('M12323')
              // close()
              props.handleOk() // 关闭换货弹窗
              return Promise.resolve()
            },
            onOk: () => {
              props.handleOk() // 关闭换货弹窗
            },
            content: (
              <div>
                <div className={Styles.flexwrap}>
                  <div>成功数：<span className={Styles['success']}>{data.successNum}</span></div>
                  <div>失败数：<span className={Styles['fail']}>{data.failNum}</span></div>
                </div>
                {/* <div>失败原因：</div> */}
                {data.failNum > 0 && <div style={{fontSize: 12, marginTop:10}}>
                  失败原因可能是：
                  {data.replacedNotExistOrderNoList.length > 0 && <div>被替换的商品编码不存在：{data.replacedNotExistOrderNoList.toString()}</div>}
                  {data.replaceNotExistOrderNoList.length > 0 && <div>替换的商品编码不存在：{data.replaceNotExistOrderNoList.toString()}</div>}
                  {data.formulaNotExistOrderNoList.length > 0 && <div>公式里填写的以下商品编码不存在：{data.formulaNotExistOrderNoList.toString()}</div>}
                  {data.replacedNotExistOrderNoList.length == 0 && 
                    data.replaceNotExistOrderNoList.length == 0 && 
                    data.formulaNotExistOrderNoList.length == 0 && 
                    <div>订单无对应的被替换的商品编码和数量，或订单是异常已支付的代发订单</div>}
                </div>}
                {/* {
                  data.msg.split('\n').map(v => {
                    return (
                      <div key={v}>{v}</div>
                    )
                  })
                } */}
                {/* <Button onClick={() => {
                  cpText('M12323')
                }}>批量复制订单号</Button> */}
                {/* <div>{data.msg.replace}</div> */}
              </div>
            )
          })
        }
        const { resultHandleType, payAmount, tradeNo } = data;
        stageParams.current = { ...params, tradeNo };
        if(typeof resultHandleType == 'object' || resultHandleType == 1){
          message.success(msg);
          props.handleOk?.();
          props.handleCancel?.();
        }else{
          setAmountObj(payAmount);
        }
      }
    })
  }

  //确定修改
  const handleSureModify = async (password) => {
    setLoading(true);
    const { msg, success} = await modifyGoodsOp({
      password,
      ...stageParams.current
    });
    setLoading(false);
    if(success){
      message.success(msg);
      props.handleOk?.();
      props.handleCancel?.();
    }
  }

  const orderAreaRadioSwitchProps = {
    searchForm,
    selectKeys,
    orderList,
    states: [10, 30],
    title:'仅限待审核、异常状态订单',
    updateShowNumer(obj, ids){
      filterIds.current = ids;
      setShowNumber(obj || {});
    },

    // 保存换货公式
    async saveFormula (flag) {
      const users = form.getFieldValue('users')
      const params = []
      for(let item  of users) {
        if(item?.first2){ // 过滤掉空值
          params.push(item)
        }
      }
      const res = await saveOrUpdatePageConfig({
        scope: 2,
        page: 'orderPageList',
        type: 'goods-formula',
        param: JSON.stringify(params)
      })
      if(res?.success) {
        !flag && message.success(res?.msg)
      } else {
        message.warning(res?.msg)
      }
    },
    renderInnerInputArr1: [
      {
        Component: Input,
        name: 'delSkuCodes',
        label: '被替换的商品编码',
        rules: [{ required: addStrategyWatch == 1 ? true : false, message: '编码不能为空' }],
        style: {
          marginTop: 12,
        },
        props: {
          allowClear: true, // 配置antd输入框组件
          maxLength: 200,
          suffix: (
            <Space>
              {/* <GoodsSelectModal
                setSelectedRows={(data) => {
                  return data;
                }}
                submitCallback={(val) => {
                  handleInputDeleteValue(val.map(item=> item.skuCode).join(','));
                }}
              > */}
                <IconFont type="iconmodal-input" onClick={()=>handleOpen('delete')}/>
              {/* </GoodsSelectModal> */}
              {/* 暂时去掉批量弹窗 */}
              {/* <BatchInputModal
                placeholder="被替换的商品编码，多个空格隔开"
                onChange={val => handleInputDeleteValue(val)}
              ></BatchInputModal> */}
            </Space>
          ),
          placeholder: '请选择或输入商品编码',
          style: {width: '260px'}
        },
      },
      {
        Component: Input,
        name: 'addSkuCodes',
        label: '替换的商品编码',
        rules: [{ required: addStrategyWatch == 1 ? true : false, message: '编码不能为空' }],
        style: {
          marginTop: 12,
        },
        props: {
          allowClear: true, // 配置antd输入框组件
          maxLength: 200,
          suffix: (
            <Space>
              {/* <GoodsSelectModal
                setSelectedRows={(data) => {
                  return data;
                }}
                submitCallback={(val) => {
                  handleInputDeleteValue(val.map(item=> item.skuCode).join(','));
                }}
              > */}
                <IconFont type="iconmodal-input" onClick={()=>handleOpen('add')}/>
              {/* </GoodsSelectModal> */}
              {/* <BatchInputModal
                placeholder="替换的商品编码，多个空格隔开"
                onChange={val => handleInputDeleteValue(val)}
              ></BatchInputModal> */}
            </Space>
          ),
          placeholder: '请选择或输入商品编码',
        },
      },
    ],
    renderInnerInputArr3: [ // form动态增减
      1
    ],
    renderInnerInputArr4: [
      {
        Component: InputNumber,
        name: 'prices',
        label: '采购价',
        rules: [{ required: addStrategyWatch == 4 ? true : false, message: '请输入' }],
        style: {
          marginTop: 12,
        },
        props: {
          allowClear: true, // 配置antd输入框组件
          // defaultValue:"0.01",
          min:"0.01",
          max:"999999",
          step:"0.01",
          suffix: (
            <Space>
                元
            </Space>
          ),
          placeholder: '请选择或输入商品编码',
          style: {width: '260px'}
        },
      },
    ],
  }
  const orderAreaRadioProps = {
    searchForm,
    selectKeys,
    orderList,
    states: [10, 30],
    title:'仅限待审核、异常状态订单',
    updateShowNumer(obj, ids){
      filterIds.current = ids;
      setShowNumber(obj || {});
    }
  }

  const confirmPayModalProps = {
    amountObj,
    handleOk: handleSureModify,
    handleCancel(){
     setAmountObj(null);
    },
  }

  //批量添加
  const handleInputAddValue = (value) => {
    const oldValue = form.getFieldValue('addSkuCodes');
    const newCombineValue = combindStr2(oldValue, value);
    form.setFieldValue('addSkuCodes', newCombineValue);
  }

  //批量删除
  const handleInputDeleteValue = (value) => {
    const oldArr = stringFormatArr(form.getFieldValue('delSkuCodes')),
    newArr = stringFormatArr(value),
    allArr = [...new Set([...oldArr, ...newArr])];
    form.setFieldValue('delSkuCodes', allArr.join(','));
  }

  const handleOpen = (typeValue) =>{
    operatorType.current = typeValue;
    setVisible(true)
  }

  const modalProps = {
    selectTitle: '选择商品',
    handleCancel() {
      setVisible(false);
    },
    onGoodsSkuListSelected(values) {
      console.log(values, '弹窗传值')
      if(operatorType.current == 'add'){
        handleInputAddValue(values.map(item=> `${item.skuCode}*${item.num || 1}`).join(','));
      }else{
        handleInputDeleteValue(values.map(item=> item.skuCode).join(','));
      }
    },
    destroyOnClose: true,
    isNotShow: operatorType.current == 'delete' // 去掉组合商品
};

  const RNode = (props)=> {
    console.log(props.children, 44)
    return props.children
  }

  return (
    <CommonModal zIndex={222} specWrapperStyle={{'max-height': '60vh'}}  title={{ title: '批量换货' }} open={true} width="630px" onOk={handleOk} onCancel={props.handleCancel}>
      {/* 提示文字 */}
      <Alert className={Styles.fsize} message="支持待审核和异常订单。异常订单里，如果是异常已支付的代发订单，则会跳过" type="info" />
      {/* <RNode sl='abc'>
        <div abc='adf'>

        <div ts='as'>1
          <div>saf</div>
        </div>
        <div ts='af'>32</div>
        </div>
      </RNode> */}
      <CommonForm
        formProps={{
          form,
          initialValues: {addStrategy: 1, users: [{}], prices: 0.02} // 动态表单设置默认值initialValues
        }
      }
      
        columns={[
          {
            name: 'radio-group',
            slot: <OrderAreaRadioGroup {...orderAreaRadioProps} />,
          },
          {
            block: (
              <>
                <OrderNumberCount
                  data={[
                    { label: '待审核', value: showNumber[10], type: 'warning' },
                    { label: '异常', value: showNumber[30], type: 'error' },
                  ]}
                />
                {/* <SubTitle symbol as="s2" title="修改方式" wrapStyle={{ marginTop: 16 }} /> */}
              </>
            ),
          },
          // {
          //   Component: Input,
          //   name: 'delSkuCodes',
          //   style: {
          //     marginTop: 12,
          //   },
          //   props: {
          //     suffix: (
          //       <Space>
          //         {/* <GoodsSelectModal
          //           setSelectedRows={(data) => {
          //             return data;
          //           }}
          //           submitCallback={(val) => {
          //             handleInputDeleteValue(val.map(item=> item.skuCode).join(','));
          //           }}
          //         > */}
          //           <IconFont type="iconmodal-input" onClick={()=>handleOpen('delete')}/>
          //         {/* </GoodsSelectModal> */}
          //         <BatchInputModal
          //           placeholder="删除指定商品，多个空格隔开"
          //           onChange={val => handleInputDeleteValue(val)}
          //         ></BatchInputModal>
          //       </Space>
          //     ),
          //     placeholder: '删除指定商品，多个逗号隔开',
          //   },
          // },
          // {
          //   Component: Input,
          //   name: 'addSkuCodes',
          //   style: {
          //     marginTop: 12,
          //   },
          //   props: {
          //     placeholder: '添加指定商品*数量，多个空格隔开',
          //     suffix: (
          //       <Space>
          //         {/* <GoodsSelectModal
          //           type={2}
          //           setSelectedRows={(data) => {
          //             return data;
          //           }}
          //           submitCallback={(val, obj) => {
          //             handleInputAddValue(val.map(item=> `${item.skuCode}*${obj[item.id] || 1}`).join(','));
          //           }}
          //         > */}
          //           <IconFont type="iconmodal-input" onClick={()=>handleOpen('add')}/>
          //         {/* </GoodsSelectModal> */}
          //         <BatchInputModal
          //           placeholder="添加指定商品，多个逗号隔开"
          //           onChange={val => handleInputAddValue(val)}
          //         ></BatchInputModal>
          //       </Space>
          //     ),
          //   },
          // },
          // {
          //   block: <SubTitle symbol as="s2" title="修改方式" wrapStyle={{ marginTop: 16 }} />,
          // },
          {
            name: 'addStrategy', // 不能通过form实例get取值
            slot: <OrderAreaRadioGroup1Switch {...orderAreaRadioSwitchProps} />,
          },
        ]}
      ></CommonForm>
      {amountObj && <ConfirmPayModal {...confirmPayModalProps} />}
      { visible && <GoodsListModal {...modalProps} />}
      <CommonLoading loading={loading} />
    </CommonModal>
  );
}

export default React.memo(ResetStyle(UpdateGoodsModal, { wrappers: ['rule-reset'] }));
